//
//  DR_SortActionSheet.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit

enum DR_SortType: String, CaseIterable {
    case oldestFirst = "Oldest First"
    case newestFirst = "Newest First"
    case nameAToZ = "Name (A To Z)"
    case nameZToA = "Name (Z To A)"
    case sizeSmallest = "Size (Smallest)"
    case sizeLargest = "Size (Largest)"
}

class DR_SortActionSheet: UIView {
    
    var onSortSelected: ((DR_SortType) -> Void)?
    var onDismiss: (() -> Void)?
    
    private var selectedSortType: DR_SortType = .oldestFirst
    private var sortViews: [UIView] = []
    
    private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        return view
    }()
    
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "sort_title".localized
        label.font = UIFont.systemFont(ofSize: 15)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    
    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "more_close"), for: .normal)
        return button
    }()
    
    private let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .white
        scrollView.showsVerticalScrollIndicator = false
        return scrollView
    }()
    
    private let contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private let topLineView: UIView = {
        let view = UIView()
        view.backgroundColor = "#F5F5F5".toColor
        return view
    }()
    
    private let bottomLineView: UIView = {
        let view = UIView()
        view.backgroundColor = "#F5F5F5".toColor
        return view
    }()
    
    private let cancelButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("common_cancel".localized, for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(backgroundView)
        addSubview(containerView)
        
        containerView.addSubview(titleLabel)
        containerView.addSubview(closeButton)
        containerView.addSubview(scrollView)
        containerView.addSubview(cancelButton)
        containerView.addSubview(topLineView)
        containerView.addSubview(bottomLineView)
                
        scrollView.addSubview(contentView)
        
        // 创建排序选项视图
        for (index, sortType) in DR_SortType.allCases.enumerated() {
            let sortView = createSortView(sortType: sortType, index: index)
            contentView.addSubview(sortView)
            sortViews.append(sortView)
        }
    }
    
    private func setupConstraints() {
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        containerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(320)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(18)
        }
        
        closeButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(16)
            make.width.height.equalTo(24)
        }
        
        cancelButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-30)
            make.height.equalTo(18)
            make.width.equalTo(200)
        }
        
        topLineView.snp.makeConstraints { make in
            make.trailing.leading.equalToSuperview().inset(15)
            make.top.equalTo(closeButton.snp.bottom).offset(13)
            make.height.equalTo(1)
        }
        
        bottomLineView.snp.makeConstraints { make in
            make.trailing.leading.equalToSuperview()
            make.bottom.equalTo(cancelButton.snp.top).offset(-12)
            make.height.equalTo(5)
        }
        
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(topLineView.snp.bottom).offset(8)
            make.bottom.equalTo(bottomLineView.snp.top).offset(-8)
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        // 排序选项布局
        for (index, sortView) in sortViews.enumerated() {
            sortView.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview().inset(20)
                make.height.equalTo(40)
                if index == 0 {
                    make.top.equalToSuperview().offset(0)
                } else {
                    make.top.equalTo(sortViews[index - 1].snp.bottom).offset(4.5)
                }
            }
        }
        
        // 设置contentView的底部约束
        if let lastView = sortViews.last {
            lastView.snp.makeConstraints { make in
                make.bottom.equalToSuperview().offset(-12)
            }
        }
    }
    
    private func setupActions() {
        backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss)))
        closeButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        cancelButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
    }
    
    private func createSortView(sortType: DR_SortType, index: Int) -> UIView {
        let container = UIView()
        container.backgroundColor = .clear
        
        let label = UILabel()
        label.text = sortType.rawValue
        if sortType.rawValue == "Oldest First" {
            label.text = "sort_oldest".localized
        }else if sortType.rawValue == "Newest First" {
            label.text = "sort_newest".localized
        }else if sortType.rawValue == "Name (Z to A)" {
            label.text = "sort_nameZ".localized
        }else if sortType.rawValue == "Name (A to Z)" {
            label.text = "sort_nameA".localized
        }
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = .center
        label.textColor = .black
        
        let checkImageView = UIImageView()
        checkImageView.image = UIImage(named: "language_check")
        checkImageView.contentMode = .scaleAspectFill
        checkImageView.isHidden = sortType != selectedSortType
        
        container.addSubview(label)
        container.addSubview(checkImageView)
        
        label.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
        }
        
        checkImageView.snp.makeConstraints { make in
            make.leading.equalTo(label.snp.trailing).offset(12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        // 设置选中状态
        if sortType == selectedSortType {
            label.textColor = "#333FFF".toColor
        }
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(sortTapped(_:)))
        container.addGestureRecognizer(tapGesture)
        container.isUserInteractionEnabled = true
        container.tag = index
        
        return container
    }
    
    @objc private func sortTapped(_ gesture: UITapGestureRecognizer) {
        guard let view = gesture.view else { return }
        let index = view.tag
        
        if index < DR_SortType.allCases.count {
            selectedSortType = DR_SortType.allCases[index]
            updateSortViews()
            // 选择后立即关闭并触发回调
            onSortSelected?(selectedSortType)
            hide()
        }
    }
    
    private func updateSortViews() {
        for (index, sortView) in sortViews.enumerated() {
            if index < DR_SortType.allCases.count {
                let sortType = DR_SortType.allCases[index]
                let isSelected = sortType == selectedSortType
                
                // 更新文字颜色
                for subview in sortView.subviews {
                    if let label = subview as? UILabel {
                        if isSelected {
                            label.textColor = "#333FFF".toColor
                        } else {
                            label.textColor = .black
                        }
                        break
                    }
                }
                
                // 更新对勾图标（查找 UIImageView）
                for subview in sortView.subviews {
                    if let checkImageView = subview as? UIImageView {
                        checkImageView.isHidden = !isSelected
                        break
                    }
                }
            }
        }
    }
    
    @objc private func dismiss() {
        hide()
    }
    
    func show(in parentView: UIView, currentSort: DR_SortType = .oldestFirst) {
        selectedSortType = currentSort
        updateSortViews()
        
        parentView.addSubview(self)
        parentView.bringSubviewToFront(self)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: parentView.topAnchor),
            self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
        ])
        
        // 初始状态：背景透明，容器在底部外
        backgroundView.alpha = 0
        containerView.transform = CGAffineTransform(translationX: 0, y: 320)
        
        // 强制布局
        layoutIfNeeded()
        
        // 再次确保在最上层
        parentView.bringSubviewToFront(self)
        
        // 动画显示
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
            self.backgroundView.alpha = 1
            self.containerView.transform = .identity
        } completion: { _ in
            parentView.bringSubviewToFront(self)
        }
    }
    
    func hide() {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.backgroundView.alpha = 0
            self.containerView.transform = CGAffineTransform(translationX: 0, y: 320)
        } completion: { _ in
            self.removeFromSuperview()
            self.onDismiss?()
        }
    }
}

